package com.Utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;


import java.util.ArrayList;
import java.util.Map;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;



public class HttpClientUtil {



    //封装传递键值对格式的get请求
    public static String sendGet(String url, Map<String, String> params) {
        String result = "";
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            StringBuilder uriBuilder = new StringBuilder(url);
            // 设置参数
            if (params != null && !params.isEmpty()) {
                uriBuilder.append("?");
                List<BasicNameValuePair> pairList = new ArrayList<>();
                params.forEach((key, value) -> pairList.add(new BasicNameValuePair(key, value)));
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8);
                // 将参数转成page=1&limit=5格式
                result = EntityUtils.toString(urlEncodedFormEntity, StandardCharsets.UTF_8);
                uriBuilder.append(result);
            }

            HttpGet httpGet = new HttpGet(uriBuilder.toString());
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    // 处理错误情况
                    throw new IOException("Unexpected response status: " + response.getStatusLine().getStatusCode());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    //封装传递键值对格式的post请求 application/x-www-form-urlencoded
    public static String sendPost(String url, Map<String, String> params) {
        String result = "";
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置参数
            if (params != null && !params.isEmpty()) {
                List<BasicNameValuePair> pairList = new ArrayList<>();
                params.forEach((key, value) -> pairList.add(new BasicNameValuePair(key, value)));
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    throw new IOException("Unexpected response status: " + response.getStatusLine().getStatusCode());
                }
            }
        } catch (IOException e) {
            e.printStackTrace(); // 在实际应用中可以改为日志记录
        }
        return result;
    }


    //封装传递Json格式的post请求
    public static String sendPostJson(String url, Map<String, String> params) {
        String result = "";
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置参数
            if (params != null && !params.isEmpty()) {
                String paramJson = JSONObject.toJSONString(params);
                StringEntity stringEntity = new StringEntity(paramJson, StandardCharsets.UTF_8);
                stringEntity.setContentType("application/json;charset=utf-8");
                httpPost.setEntity(stringEntity);
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    throw new IOException("Unexpected response status: " + response.getStatusLine().getStatusCode());
                }
            }
        } catch (IOException e) {
            e.printStackTrace(); // 在实际应用中可以改为日志记录
        }
        return result;
    }


    /**
     * 发送Post multipart/form-data请求
     */

    public static String MultipartFormData(String urlString, List<BasicNameValuePair> params, String filePath) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

        // 设置请求方法和其他属性
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Cache-Control", "no-cache");

        // 构建边界字符串
        String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
        httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        // 写入请求体
        try (OutputStream outputStream = httpConn.getOutputStream();
             PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true)) {

            // 添加文本参数
            for (BasicNameValuePair param : params) {
                writer.append("--" + boundary).append("\r\n")
                        .append("Content-Disposition: form-data; name=\"" + param.getName() + "\"").append("\r\n")
                        .append("Content-Type: text/plain; charset=UTF-8").append("\r\n")
                        .append("\r\n") // 空行分隔头部和内容
                        .append(param.getValue()).append("\r\n");
            }

            // 添加文件参数
            File file = new File(filePath);
            writer.append("--" + boundary).append("\r\n")
                    .append("Content-Disposition: form-data; name=\"file_content\"; filename=\"" + file.getName() + "\"").append("\r\n")
                    .append("Content-Type: " + getContentType(file)).append("\r\n")
                    .append("\r\n"); // 空行分隔头部和内容

            writer.flush();

            try (FileInputStream inputStream = new FileInputStream(file)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }

            writer.append("\r\n").flush(); // 文件内容后添加换行符
            writer.append("--" + boundary + "--").append("\r\n").flush(); // 结束边界
        }

        // 获取响应码
        int responseCode = httpConn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 成功时处理响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } else {
            // 失败时返回错误信息
            throw new IOException("Unexpected response status: " + responseCode);
        }
    }


    private static String getContentType(File file) {
        // 根据文件扩展名简单判断内容类型
        String fileName = file.getName().toLowerCase();
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        }
        if (fileName.endsWith(".png")) {
            return "image/png";
        }
        if (fileName.endsWith(".gif")) {
            return "image/gif";
        }
        if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        }
        // 默认返回八位流类型
        return "application/octet-stream";
    }
}



